package com.redis.test03;

import com.alibaba.fastjson.JSON;
import com.redis.test02.MyRedisUtil;
import com.redis.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 作者: LCG
 * 日期: 2019/9/10 17:57
 * 描述:
 */

@Component
public class TestService {

    @Autowired
    private TestMapper testMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Transactional
    public void toLockStock(Map<String,Object> map){

        boolean lock = MyRedisUtil.getLock(map.get("key").toString(), map.get("requestId").toString(), redisTemplate, "50");

        if(lock){

            Map<String, Object> byId = testMapper.getById(1L);

            Object stock = byId.get("stock");

            byId.put("stock",Integer.valueOf(stock.toString())-1);

            testMapper.updateGoodsStock(byId);

            MyRedisUtil.unLock(map.get("key").toString(), map.get("requestId").toString(), redisTemplate);

        }else{

            String sm = JSON.toJSONString(map);
            //入队操作
            redisTemplate.convertAndSend("TEST",sm);
        }

    }

}
